package com.aiwhose.aiwhosewechatplublicaiwhose.controller;


import cn.hutool.core.util.StrUtil;
import cn.hutool.core.util.XmlUtil;
import cn.hutool.crypto.SecureUtil;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.aiwhose.aiwhosewechatplublicaiwhose.utils.WXPlublicUtil;
import com.aiwhose.aiwhosewechatplublicaiwhose.utils.message.WXMessageCustomerUtil;
import jakarta.annotation.Resource;
import jakarta.servlet.ServletInputStream;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;
import org.w3c.dom.Document;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.Arrays;
import java.util.Map;

@CrossOrigin
@RestController
@RequestMapping("/plublic")
@Slf4j
public class WXPlublicController {
    @Resource
    WXPlublicUtil wxPlublicUtil;
    @Resource
    WXMessageCustomerUtil wxMessageCustomerUtil;
    @Value("${wechat_public.token}")
    private String token;
    @GetMapping("/weichatTest")
    public String weichatTest(HttpServletRequest request, HttpServletResponse response) throws IOException {
        String echostr = null;
        //token验证代码段

        log.info("请求已到达，开始校验token");
        //这里对应的文档里面的几个参数，如果不清楚，请查看文档
        if (StrUtil.isNotBlank(request.getParameter("signature"))) {
            echostr = request.getParameter("echostr");
            if (checkSignature(request)) {
                log.info("数据源为微信后台，将echostr[{}]返回！", echostr);
                response.getOutputStream().println(echostr);
                return echostr;
            }
        }
        return echostr;
    }

    @PostMapping("/weichatTest")
    public String weichatTestPost(HttpServletRequest request, HttpServletResponse response) throws IOException, InterruptedException {
        boolean signature = checkSignature(request);
        if (!signature) {
            return "你个大可爱，不要攻击我的服务器！";
        }
        ServletInputStream inputStream = request.getInputStream();
        // 使用 BufferedReader 读取输入流
        BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream));

        // 读取输入流内容并拼接成字符串
        StringBuilder sb = new StringBuilder();
        String line;
        while ((line = reader.readLine()) != null) {
            sb.append(line);
        }

        // 将输入流内容转换为字符串
        String inputStreamContent = sb.toString();
        Document document = XmlUtil.readXML(inputStreamContent);
        String jsonStr = JSONUtil.toJsonStr(XmlUtil.xmlToMap(document));
        JSONObject entries = JSONUtil.parseObj(jsonStr);
        JSONObject xml = entries.getJSONObject("xml");

        wxMessageCustomerUtil.InputState(xml.getStr("FromUserName"), "Typing");
        String service = serviceSelection(xml);
        wxMessageCustomerUtil.InputState(xml.getStr("FromUserName"), "CancelTyping");
        return service;
    }


    private String serviceSelection(Map<String, Object> xml) throws InterruptedException, IOException {
        String msgType = xml.get("MsgType").toString();

        return switch (msgType) {
            case "text" -> wxPlublicUtil.handleTextMessage(xml);
            case "image" -> wxPlublicUtil.handleImageMessage(xml);
            case "voice" -> wxPlublicUtil.handleVoiceMessage(xml);
            case "video" -> wxPlublicUtil.handleVideoMessage(xml);
            case "shortvideo" -> wxPlublicUtil.handleShortVideoMessage(xml);
            case "location" -> wxPlublicUtil.handleLocationMessage(xml);
            case "link" -> wxPlublicUtil.handleLinkMessage(xml);
            case "event" -> wxPlublicUtil.handleEventMessage(xml);
            default -> "Unsupported message type";
        };
    }

    /**
     * 校验是否为微信服务器发来的请求
     *
     * @param request
     * @return
     */

    public boolean checkSignature(HttpServletRequest request) {
        String echostr = null;
        //token验证代码段

        log.info("请求已到达，开始校验token");
        //这里对应的文档里面的几个参数，如果不清楚，请查看文档
        if (StrUtil.isNotBlank(request.getParameter("signature"))) {
            String signature = request.getParameter("signature");
            String timestamp = request.getParameter("timestamp");
            String nonce = request.getParameter("nonce");
            echostr = request.getParameter("echostr");
            log.info("signature[{}], timestamp[{}], nonce[{}], echostr[{}]", signature, timestamp, nonce, echostr);

            String[] str = new String[]{token, timestamp, nonce};
            //排序
            Arrays.sort(str);
            //拼接字符串
            StringBuffer buffer = new StringBuffer();
            for (int i = 0; i < str.length; i++) {
                buffer.append(str[i]);
            }
            //进行sha1加密
            String temp = SecureUtil.sha1(buffer.toString());
            //与微信提供的signature进行匹对
            return signature.equals(temp);

        } else {
            return false;
        }


    }


}
